﻿using System;
using System.Web.WebPages;
using Eksponent.RazorRocks.Helpers;

namespace Eksponent.RazorRocks
{
    public delegate HelperResult TemplateRenderAction<in TItem>(TItem item, dynamic parameters);


    public class DelegateTemplateAction<TItem> : TemplateAction<TItem>
    {
        public class Args
        {
            public TItem Instance { get; set; }
            public dynamic Parameters { get; set; }
        }

        public TemplateRenderAction<TItem> RenderAction { get; set; }

        public DelegateTemplateAction(TemplateRenderAction<TItem> renderAction)
        {
            RenderAction = renderAction;
        }        


        public override TemplateHelperResult Render(TItem item, TemplateRenderContext<TItem> context)
        {            
            return 
                new TemplateHelperResult(w=>
                                             {
                                                 var res = RenderAction(item, new DynamicDictionary(context.Parameters));
                                                 if( res != null )
                                                 {
                                                     res.WriteTo(w);                                                     
                                                 }
                                             }
                                         , context.Parameters);
        }
    } 
}